package tree.leetcode_145_medium;


import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class PostorderTraversal2 {
    public static void main(String[] args) {
        PostorderTraversal2 p2 = new PostorderTraversal2();
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);
        root.left.left.left = new TreeNode(8);
        System.out.println("后序遍历：");
        printList(p2.postorderTraversal(root));
    }
    public static void printList(List<Integer> list){
        for (int i = 0; i<list.size(); i++){
            System.out.print(list.get(i)+" ");
        }
    }
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null){
            return list;
        }
        TreeNode node = root;
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        stack1.push(node);
        while(!stack1.isEmpty()){
            node = stack1.pop();
            stack2.push(node);
            if(node.left != null){
                stack1.push(node.left);
            }
            if(node.right != null){
                stack1.push(node.right);
            }
        }
        while (!stack2.isEmpty()){
            list.add(stack2.pop().val);
        }
        return list;
    }
}
